(function () {

	'use strict';

	angular
		.module('app')
		.factory('MyCardModel', MyCardModel);

    MyCardModel.$inject = ['$http', '$q', '$timeout', '$rootScope', 'CacheFactory', 'AppAuthenticationService', 'API', 'ENUM'];

	function MyCardModel($http, $q, $timeout, $rootScope, CacheFactory, AppAuthenticationService, API, ENUM) {

		var PER_PAGE = 10;
		var CURRENT_PAGE = 1;
		var TOTAL_PAGE = 1;

		var service = {};
		service.isEmpty = false;
		service.isLoaded = false;
		service.isLoading = false;
		service.isLastPage = false;
		service.status = null;
		service.cards = null;
		service.count = null;
		service.fetch = _fetch;
		service.reload = _reload;
		service.loadMore = _loadMore;
		return service;

		function _reload() {

			if (!AppAuthenticationService.getToken())
				return;

			if (this.isLoading)
				return;

			this.cards = null;
			this.count = null;
			this.isEmpty = false;
			this.isLoaded = false;
			this.isLastPage = false;

			this.fetch(1, PER_PAGE);
		}

		function _loadMore() {

			if (!AppAuthenticationService.getToken())
				return;

			if (this.isLoading)
				return;
			if (this.isLastPage)
				return;

            if (CURRENT_PAGE < TOTAL_PAGE) {
                this.fetch(CURRENT_PAGE + 1, PER_PAGE);
            } else {
                this.fetch(1, PER_PAGE);
            }
		}

		function _fetch(page, perPage) {

			if (!AppAuthenticationService.getToken())
				return;

			this.isLoading = true;

			var params = {
				page: page,
				per_page: perPage
			};

			if (null != this.status) {
				params.status = this.status;
			}

			var _this = this;
            API.card.getCardCount().then(function (res) {
                _this.count = res;

            });
			API.card.getOrderCard(params).then(function (res) {
				_this.cards = _this.cards ? _this.cards.concat(res.rows) : res.rows;
                CURRENT_PAGE = res.current_page;
                TOTAL_PAGE = res.total_page;
				_this.isEmpty = (res.total) ? false : true;
				_this.isLoaded = true;
				_this.isLoading = false;
				_this.isLastPage = (res.current_page==res.total_page) ? true : false;
			});
		}

	}

})();